﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Data;
using System.Xml;
using System.Net.Mail;
using System.Configuration;
using System.Text;

namespace Documents
{
    public class Functions
    {
        private static string xmlPath = HttpContext.Current.Server.MapPath("App_Data/DownLoadFiles.xml");

        public static void AddSourceUsers(string mail, string keyId)
        {
            DataSet ds = GetItems();

            DataTable dt = ds.Tables["sourceDownload"];
            dt.Rows.Add(new object[] { mail, keyId, DateTime.Now });

            ds.WriteXml(xmlPath, XmlWriteMode.WriteSchema);
        }

        public static int GetSourceUserCount() {
            DataTable dt = GetItems("sourceDownload");
            return dt.Rows.Count;
        }

        public static bool IsKeyIdAvailableL(string keyId)
        {
            return false;
        }

        public static void WriteUpdateItems(DataTable dt)
        {
            dt.DataSet.WriteXml(xmlPath, XmlWriteMode.WriteSchema);
        }

        public static string GetSourceFileName()
        {
            XmlDocument xml = new XmlDocument();
            xml.Load(xmlPath);
            XmlNode node = xml.SelectSingleNode("//Files/sourceFile");
            if (node == null) return string.Empty;
            string f = node.Attributes["name"].Value;
            return f;
        }

        public static bool SendEmail(string toMail, string subject, string content)
        {
            MailMessage e = new MailMessage();
            e.To.Add(toMail);
            e.From = new MailAddress(ConfigurationManager.AppSettings["mailFrom"]);
            e.Body = content;
            e.IsBodyHtml = true;
            e.Subject = subject;
            e.SubjectEncoding = Encoding.UTF8;
            e.BodyEncoding = Encoding.UTF8;

            try
            {
                SmtpClient client = new SmtpClient();
                client.Credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["mailUser"], ConfigurationManager.AppSettings["mailPsw"]);
                client.Host = ConfigurationManager.AppSettings["mailSmtp"];
                object userState = e;
                client.Send(e);
                return true;
            }
            catch (Exception ex)
            {
                uoLib.Web.Debugger.ErrorReporter.RecordErrors(ex);
                return false;
            }
        }

        public static DataTable GetItems(string tableName)
        {
            DataSet ds = GetItems();
            if (ds == null) return null;
            DataTable dt = ds.Tables[tableName];
            return dt;
        }

        private static DataSet GetItems()
        {
            DataSet ds = new DataSet();
            ds.ReadXml(xmlPath);
            return ds;
        }
    }
}
